const http = require('http')
const url = require('url')

console.log(process.argv)
const port = process.argv.length >= 3 ? Number(process.argv[2]) : 3000

http.createServer(function (request, response) {
  handleResponse(response)

  let encodedUrl = request.url.substring(1)
  let decodedUrl = decodeURIComponent(encodedUrl)

  let { protocol, hostname, port, path, host } = url.parse(encodedUrl)
  let method = request.method
  let headers = request.headers
  headers['host'] = host

  let requestOptions = {
    protocol,
    hostname,
    port,
    path,
    method: method,
    headers: headers
  }
  console.log('Request options', requestOptions)

  let checkedError = check(requestOptions)
  if (checkedError) {
    let errorData = {
      code: 'BAD_URL',
      message: checkedError
    }
    response.writeHead(400, { 'Content-Type': 'application/json' })
    response.end(JSON.stringify(errorData))
    return
  }

  let targetRequest = http.request(requestOptions, function (targetResponse) {
    let { statusCode, statusMessage, headers } = targetResponse
    console.log('Response options', { statusCode, statusMessage, headers })

    response.statusCode = statusCode
    response.statusMessage = statusMessage
    for (let name in headers) {
      let value = headers[name]
      response.setHeader(name, value)
    }
    targetResponse.pipe(response)
  })

  targetRequest.on('error', function (error) {
    console.error(`Problem with request proxy: ${error}`)
    let errorData = {
      code: 'REQUEST_PROXY_ERROR',
      message: `发送代理请求时出错：${error.message}`
    }
    response.writeHead(400, { 'Content-Type': 'application/json' }) // TODO 代理错误的status code
    response.end(JSON.stringify(errorData))
  })

  request.pipe(targetRequest)
}).listen(port, err => {
  if (err) {
    console.log(`Something bad happened: ${err}.`)
  } else {
    console.log(`Server is listening on ${port}.`)
  }
})

// 统一的前置跨域处理函数
function handleResponse (clientResponse) {
  clientResponse.setHeader("Access-Control-Allow-Origin", "*")
}

function check (requestOptions) {
  if (!requestOptions.protocol) {
    return '请求的URL缺失protocol部分'
  }
  if (!requestOptions.hostname) {
    return '请求的URL缺失hostname部分'
  }
}
